import { createSelector } from 'reselect'
import { reqCoupon } from "../../http/api";

// 1.初始值
const initState = {
    list: [],
    // 初始化n
    n: 0
}

// types
const types = {
    COUPON_CHANGE_LIST: "COUPON_CHANGE_LIST",
    COUPON_CHANGE_N: "COUPON_CHANGE_N"
}
// reducer
export const couponReducer = (state = initState, action) => {
    switch (action.type) {
        case types.COUPON_CHANGE_LIST:
            return {
                ...state,
                list: action.list
            }
            break;
        case types.COUPON_CHANGE_N:
            return {
                ...state,
                n: action.n
            }
            break;
        default:
            return state
    }
}
// actions
export const actions = {
    changeList: list => ({ type: types.COUPON_CHANGE_LIST, list }),
    changeN: n => ({ type: types.COUPON_CHANGE_N, n }),
    // 发请求
    reqListAction: () => {
        return (dispatch, getState) => {
            // 发请求
            reqCoupon().then(res => {
                if (res.data.code === 200) {
                    dispatch(actions.changeList(res.data.list))
                }
            })
        }
    }

}


// 导出数据
export const getList = state => state.coupon.list
export const getN = state => state.coupon.n
// 5.6 因为要根据n和allGoods计算出最终在页面中展示的数据，所以要将最终展示的数据导出
export const getShowList = createSelector([getList,getN],(list,n)=>{
    console.log("===========计算了计算了计算了,只需要计算一次，所以要用到getState==============");
    return list.length > 0 ? list[n].content : []
})